﻿#include "fetcher.h"
#include "ui_fetcher.h"

Fetcher::Fetcher(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Fetcher)
{
    ui->setupUi(this);

    table=G_FETCH;
    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
    ui->tableView->verticalHeader()->hide();
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);

    updateView();
    createMenu();
}

Fetcher::~Fetcher()
{
    delete ui;
}

void Fetcher::generateMenu()
{
    menu->addAction(QStringLiteral("添加... (F1)"),this,&Fetcher::addItem);
    menu->addAction(QStringLiteral("更新视图 (F5)"),this,&Fetcher::updateView);
}

void Fetcher::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_F1:
        addItem();
        break;
    case Qt::Key_F5:
        updateView();
        break;
    }
}

void Fetcher::addItem()
{
    ItemAdd item(table);
    if(item.exec() == QDialog::Accepted)
        updateView();
}

void Fetcher::updateView()
{
    model->setTable(table);
    model->setSort(0,Qt::DescendingOrder);    // 注意是倒序
    model->select();

    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("文件名|标题"));    //label
    ui->tableView->setColumnWidth(1,LAB_WID);
    ui->tableView->hideColumn(2);   //detail
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("备注"));    //addition
    ui->tableView->setColumnWidth(3,300);
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("状态"));    //status
}

void Fetcher::on_tableView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString detail=sp_fetchString(index,2);
        qApp->clipboard()->setText(detail);
    }
}

void Fetcher::on_kw_returnPressed()
{
    QString kw=ui->kw->text().trimmed();
    if(kw.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("label like '%%1%'").arg(kw));
    model->select();
}
